<template>
  <div class="safe-container">
    <van-nav-bar title="这是属于你的小日子~">
      <template #left>
        <span @click="$router.back()">
          <svg-icon style="margin-left: 10px;" icon-class='fanhui' width="30px" height="30px" class="icon"/>
        </span>
      </template>
      <template #right>
        <span @click="isSwipeShow = true">
          <svg-icon style="margin-right: 10px;" icon-class='xin-qianyue' width="30px" height="30px" class="icon"/>
        </span>
      </template>
    </van-nav-bar>
    <van-swipe ref="swipe" :touchable="touchable" v-if="isSwipeShow">
      <van-swipe-item>
        <div class="question">
          <svg-icon style="transform: rotateZ(90deg)" icon-class='xianhua' width="10px" height="10px" class="icon"/>
          您最近一次来大姨妈的日子是？
          <svg-icon style="transform: rotateZ(-90deg)" icon-class='xianhua' width="10px" height="10px" class="icon"/>
        </div>
        <van-datetime-picker
          v-model="currentDate"
          type="month-day"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
          visible-item-count="3"
          @confirm="onTimePickConfirm"
        >
          <template #confirm>
            <svg-icon icon-class='right' width="22px" height="22px" class="icon"/>
          </template>
          <template #cancel>
            <svg-icon style="opacity: 0" icon-class='right' width="0px" height="0px" class="icon"/>
          </template>
        </van-datetime-picker>
      </van-swipe-item>
      <van-swipe-item>
        <div class="question">
          <svg-icon style="transform: rotateZ(90deg)" icon-class='xianhua' width="10px" height="10px" class="icon"/>
          您一次来姨妈是多少天呢？
          <svg-icon style="transform: rotateZ(-90deg)" icon-class='xianhua' width="10px" height="10px" class="icon"/>
        </div>
        <van-picker
          show-toolbar
          :columns="columns"
          @confirm="onConfirm"
          @cancel="onCancel"
        >
          <template #confirm>
            <svg-icon icon-class='right' width="22px" height="22px" class="icon"/>
          </template>
          <template #cancel>
            <svg-icon style="transform: rotateZ(-180deg)" icon-class='right' width="22px" height="22px"
                      class="icon"/>
          </template>
        </van-picker>
      </van-swipe-item>
      <van-swipe-item>
        <div>恭喜！已经完成信息填写啦！</div>
        <svg-icon icon-class='succeed' width="180px" height="180px" class="icon"/>
        <van-button class="finishBtn" @click="submitDate">好的！</van-button>
      </van-swipe-item>
    </van-swipe>
    <EchartView @dateState="dateStateFn" :endDate="dateObj.endDate" :startDate="dateObj.startDate"
                v-else></EchartView>
    <div class="period">
      <div class="date">
        <div>今天</div>
        <div>{{ dayjs().format('MM-DD') }}&nbsp;&nbsp;{{ dayjs().format('dddd') }}</div>
      </div>
      <svg-icon style="margin-left: 10px;" icon-class='right' width="30px" height="30px" class="icon"/>
      <div class="dateState">
        {{ dateStateFather ? dateStateFather : '安全期' }}
        <svg-icon style="margin-left: -5px;" v-if="dateStateFather==='经期'" icon-class='weishengjin' width="25px"
                  height="25px" class="icon"/>
        <svg-icon style="margin-left: -5px;" v-if="dateStateFather==='排卵期'" icon-class='luanchao' width="25px"
                  height="25px" class="icon"/>
        <svg-icon style="margin-left: -5px;" v-if="dateStateFather==='安全期'" icon-class='nannv-1' width="25px"
                  height="25px" class="icon"/>
      </div>
    </div>
    <div class="numIndex">
      <div class="phy">
        <div>{{ numIndexObj.physiologicalIndex }}<span>%</span></div>
        <div>生理指数
          <svg-icon icon-class='shentijineng' width="15px" height="15px" class="icon"/>
        </div>
      </div>
      <svg-icon style="margin-left: -10px;" icon-class='xin-chibang' width="80px" height="80px" class="icon"/>
      <div class="pre">
        <div>{{ numIndexObj.pregnancyPercentage }}<span>%</span></div>
        <div>怀孕指数
          <svg-icon style="margin-left: -10px;" icon-class='pregnant' width="25px" height="25px" class="icon"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import EchartView from '../components/EchartView.vue'
import dayjs from 'dayjs'
import { addPeriodAPI, getPeriodAPI } from '@/api'

export default {
  name: 'safeIndex',
  data () {
    return {
      minDate: new Date(2023, 0, 1),
      maxDate: new Date(2023, 12, 31),
      currentDate: new Date(),
      columns: ['2天', '3天', '4天', '5天', '6天', '7天', '8天', '9天', '10天'],
      touchable: false,
      startDate: '',
      endDate: '',
      isSwipeShow: true,
      dateStateFather: '',
      dateObj: {},
      numIndexObj: {}
    }
  },
  computed: {
    dayjs () {
      return dayjs
    }
  },
  components: {
    EchartView
  },
  created () {
    this.getPeriod()
  },
  methods: {
    // 获取用户经期
    async getPeriod () {
      try {
        const { data } = await getPeriodAPI()
        this.dateObj = data[0]
        this.numIndexObj = this.getPhysiologicalNum()
        this.isSwipeShow = false
      } catch (err) {
        console.log(err)
      }
    },
    // 添加用户经期
    async submitDate () {
      try {
        const res = await addPeriodAPI({
          startDate: this.startDate,
          endDate: this.endDate
        })
        console.log(res)
        await this.getPeriod()
        this.isSwipeShow = false
      } catch (err) {
        console.log(err)
      }
    },
    getPhysiologicalNum () {
      // 经期开始日期和结束日期
      const periodStart = this.dateObj.startDate
      const periodEnd = this.dateObj.endDate
      // 构造完整日期格式
      const currentYear = dayjs().year() // 获取当前年份
      const startDateStr = `${currentYear}-${periodStart}`
      const endDateStr = `${currentYear}-${periodEnd}`

      // 计算生理指数
      const cycleLength = 28 // 默认月经周期为28天
      const lastCycleDays = dayjs(endDateStr).diff(dayjs(startDateStr), 'day') // 上一个经期天数
      const currentCycleDays = dayjs().diff(dayjs(endDateStr), 'day') // 当前周期经过的天数
      let physiologicalIndex = ((currentCycleDays + lastCycleDays - cycleLength) / cycleLength * 100).toFixed(2)
      if (physiologicalIndex < 0) {
        physiologicalIndex = (lastCycleDays / cycleLength * 100).toFixed(2)
      }
      // return physiologicalIndex
      // 计算怀孕指数
      const ovulationDay = dayjs(startDateStr).add(14, 'day') // 排卵日为上一个周期开始日 + 14 天
      const pregnancyIndex = dayjs().diff(ovulationDay, 'day')
      const pregnancyPercentage = (pregnancyIndex / 14 * 100).toFixed(2) // 怀孕指数转为百分比并保留两位小数
      return {
        physiologicalIndex,
        pregnancyPercentage
      }
    },
    dateStateFn (dateState) {
      this.dateStateFather = dateState
    },
    formatter (type, val) {
      if (type === 'month') {
        return `${val}月`
      } else if (type === 'day') {
        return `${val}日`
      }
      return val
    },
    // 获取并格式化第一个问题选择的答案
    onTimePickConfirm (value) {
      this.startDate = dayjs(value).format('M-D')
      this.$refs.swipe.next()
    },
    // 获取并格式化第二个问题选择的答案
    onConfirm (value, index) {
      const tempDate = dayjs(this.startDate, 'M-D')
      const num = Number(value.substring(0, 1))
      this.endDate = tempDate.add(num, 'day').format('M-D')
      this.$refs.swipe.next()
    },
    onCancel () {
      this.$refs.swipe.prev()
    }
  }
}
</script>

<style scoped lang="less">
.safe-container {
  background-color: #fff;
  height: 100vh;

  ::v-deep .van-nav-bar {
    .van-nav-bar__title {
      font-size: 14px;
      letter-spacing: 1px;
    }

    &::after {
      border: none;
    }
  }

  ::v-deep .van-swipe {
    border-radius: 10px;
    margin: 20px auto;
    width: 70%;
    height: 300px;
    box-shadow: 0 2px 10px 1px rgba(0, 0, 0, 0.2);

    .van-swipe-item {
      color: #ec87c0;
      text-align: center;
      font-size: 14px;
      line-height: 60px;
      letter-spacing: 1px;

    }

    .van-swipe__indicators {
      display: none;
    }
  }

  .finishBtn {
    width: 110px;
    height: 35px;
    border-radius: 20px;
    background-color: #ec87c0;
    color: #fff;
  }

  ::v-deep .van-picker {

    .van-picker__toolbar {
      height: 30px;
      margin: auto;
      width: 200px;

      .svg-icon {
        vertical-align: top;
      }
    }
  }

  .period {
    margin-top: 20px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-evenly;

    .date {
      text-align: center;
    }

    .dateState {
      padding-right: 30px;
      color: #ec87c0;
      font-weight: bolder;
      font-size: 18px;
    }
  }

  .numIndex {
    margin-top: 50px;
    display: flex;
    justify-content: space-evenly;
    font-size: 14px;
    align-items: center;
    padding: 30px 0px;
    border-radius: 0 0 60% 60%;
    box-shadow: 0 5px 5px rgba(0, 0, 0, .4);

    .phy, .pre {
      > div:first-child {
        font-size: 22px;
        font-weight: bolder;
        text-align: center;

        span {
          font-weight: normal;
          font-size: 12px;
        }
      }

    }
  }
}
</style>
